package com.link.base.ext.autocfg.controller;


import com.link.base.user.model.CoreUser;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.ServiceException;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.core.util.JsonUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.base.ext.autocfg.model.AutoCfg;
import com.link.base.ext.autocfg.model.AutoCfgItem;
import com.link.base.ext.autocfg.service.AutoCfgItemService;
import com.link.base.ext.autocfg.service.AutoCfgService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 字段扩展配置模块，字段配置项
 * @author 姚润发
 * @date 2017/6
 */
@Controller("AutoCfgItemController")
@RequestMapping("/link/autoCfgItem")
public class AutoCfgItemController extends BasicController<AutoCfgItem> {
    private static final Logger logger = LogManager.getLogger(AutoCfgItemController.class);

    @Resource
    private AutoCfgItemService autoCfgItemService;

    @Resource
    private AutoCfgService autoCfgService;

    @Override
    public BasicService<AutoCfgItem> getBasicService() throws Exception {
        return autoCfgItemService;
    }

    /**
     * 查询字段配置行，会合并标准配置与个性化配置
     * @author 姚润发
     * @date 2017/6
     * @param qps
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/queryAutoCfgItemByExamplePage")
    @ResponseBody
    public Map<String, Object> queryAutoCfgItemByExamplePage(QueryParams qps, AutoCfgItem entity, HttpSession session,
                                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            AutoCfgItem autoCfgItem = (AutoCfgItem) BasicModel.transformClass(entity, qps);
            beforQueryAllOrExample(autoCfgItem, request);
            beforQueryExample(autoCfgItem, request);
            //t.setJoinFlag("N");
            List<AutoCfgItem> list = autoCfgItemService.getExtConfig(autoCfgItem, qps);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount((BasicModel) autoCfgItem, list.size()));
        } catch (BasicServiceException e) {
            logger.error("AutoCfgItemController捕获异常: ",e);
            result.put("success", false);
            result.put("rows", new ArrayList<AutoCfgItem>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            logger.error("AutoCfgItemController捕获异常: ",e);
            result.put("success", false);
            result.put("rows", new ArrayList<AutoCfgItem>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 导出
     */
    @Override
    @RequestMapping(value = "/queryAutoCfgItemByExamplePage/exportData")
    @ResponseBody
    public Map<String, Object> exportData(AutoCfgItem entity, QueryParams qps, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {
        logger.info("导出配置列表...");
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            ExportWriter exportWriter;
            String exportType = "xlsx";
            CoreUser user = UserUtil.getUser();
            if (null != user) {
                user.setExportType(qps.getExportFileType());
            }
            if (exportType.equals(user.getExportType())) {
                exportWriter = ExportFactory.newExcelInstance(qps);
            } else {
                exportWriter = ExportFactory.newInstance(qps);
            }
            AutoCfgItem autoCfgItem = (AutoCfgItem) BasicModel.transformClass(entity, qps);
            autoCfgItem.setJoinSubFlag(false);
            while (!qps.getStopExport()) {
                beforQueryAllOrExample(autoCfgItem, request);
                beforQueryExample(autoCfgItem, request);
                List<AutoCfgItem> list = autoCfgItemService.getExtConfig(autoCfgItem, qps);
                if (qps.getPage() == 1) {
                    qps.setTotal(list.size());
                    qps.setRows(list.size());
                }
                exportWriter.wirteData(list);
                autoCfgItem.setPage(qps.getPage());
                autoCfgItem.setTotalFlag(qps.getTotalFlag());
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (BasicServiceException e) {
            logger.error("AutoCfgItemController捕获异常: ",e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            logger.error("AutoCfgItemController捕获异常: ",e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>根据头编码获取配置信息</p>
     *
     * @param objCode
     * @param session
     * @param request
     * @param response
     * @author yrf
     */
    @RequestMapping(value = "/getExtConfig")
    //@ResponseBody
    public void getExtConfig(String objCode, Long corpId, String confType, HttpSession session,
                             HttpServletRequest request, HttpServletResponse response) {
        try {
            if (StringUtils.isBlank(objCode)) {
                throw new ServiceException("AUTOCFG-001");
            }
            if (null == corpId) {
                CoreUser user = UserUtil.getUser();
                if (user == null) {
                    throw new ServiceException("AUTOCFG-002");
                }
                corpId = user.getCorpid();
            }
            if (StringUtils.isBlank(confType)) {
                throw new ServiceException("AUTOCFG-003");
            }
            AutoCfg objExample = new AutoCfg();
            objExample.setCode(objCode);
            objExample.setPageFlag(false);
            objExample.setUnionStandardCorp(0L);
            objExample.setAnonymousFlag("Y");
            objExample.setLoginCorpId(corpId);
            objExample.setCorpid(corpId);
            objExample.setConfType(confType);
            List<AutoCfg> objList = autoCfgService.queryByExamplePage(objExample);
            if (objList == null || objList.size() == 0) {
                throw new ServiceException("AUTOCFG-004", objCode);
            }
            AutoCfgItem example = new AutoCfgItem();
            example.setHeadId(objList.get(0).getId());
            example.setPageFlag(false);
            example.setActive("Y");
            example.setAnonymousFlag("Y");
            example.setLoginCorpId(corpId);
            example.setCorpid(corpId);
            example.setJoinSubFlag(true);
            List<AutoCfgItem> list = autoCfgItemService.getExtConfig(example, null);
            if (list != null && list.size() > 0) {
                //升序排序
                Collections.sort(list, new Comparator<AutoCfgItem>() {
                    @Override
                    public int compare(AutoCfgItem o1, AutoCfgItem o2) {
                        if (o1.getSeq() == null) {
                            return -1;
                        } else if (o2.getSeq() == null) {
                            return 1;
                        } else if (o1.getSeq().equals(o2.getSeq())) {
                            return 0;
                        }
                        return o1.getSeq() > o2.getSeq() ? 1 : -1;
                    }
                });
                List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>(list.size());
                for (AutoCfgItem item : list) {
                    resultList.add(autoCfgItemService.toCfgMap(item));
                }

                String jsonStr = JsonUtil.toString(resultList);
                responseJson(request, response, jsonStr);
            } else {
                responseJson(request, response, "[]");
            }
        } catch (Exception e) {
            logger.error("AutoCfgItemController捕获异常: ",e);
            responseJson(request, response, "{\"error\":\"" + e.getMessage() + "\"}");
        }
    }

    @RequestMapping(value = "/swapSeq")
    @ResponseBody
    public Map<String, Object> getExtConfig2(Long id1,
                                             Long id2,
                                             Long corp1,
                                             Long corp2,
                                             Long headId,
                                             HttpSession session,
                                             HttpServletRequest request,
                                             HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            result = autoCfgItemService.swapSeq(id1, id2, corp1, corp2, headId);
            result.put("success", true);
        } catch (BasicServiceException e) {
            logger.error("AutoCfgItemController捕获异常: ",e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            logger.error("AutoCfgItemController捕获异常: ",e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = BasicControllerException.class)
    protected void importCsvData(List<AutoCfgItem> list, QueryParams qps, HttpServletRequest request) throws Exception {
        for (int i = 0; list != null && i < list.size(); i++) {
            AutoCfgItem record = list.get(i);
            record.setHeadId(qps.getImportParentId());
            record.setCorpid(UserUtil.getUser().getCorpid());
            beforeImport(record, request);
            getBasicService().insert(record);
        }
    }

    /**
     * <p>增删改批量操作</p>
     *
     * @param list
     * @param request
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/batchCRUD")
    @ResponseBody
    public Map<String, Object> crud(@RequestBody List<AutoCfgItem> list, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            autoCfgItemService.upsertAndDel(list);
            result.put("success", true);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("AutoCfgItemController捕获异常: ",e);
            result.put("success", false);
            result.put("result", e.getMessage());
            if (e instanceof BasicServiceException) {
                result.put("detailMessage", ((BasicServiceException) e).getDetailMessage());
            }
        }
        return result;
    }
}
